<template>
    <div class="multi-dim-report-page">
        <!-- 操作区 -->
        <div class="op-bar">
            <el-input v-model="searchKeyword" placeholder="搜索报表名称/描述" style="width:220px" @input="filterReports"
                clearable />
            <el-select v-model="selectedGroup" placeholder="分组" style="width:140px" @change="filterReports" clearable>
                <el-option label="全部分组" value="" />
                <el-option v-for="g in groupOptions" :key="g" :label="g" :value="g" />
            </el-select>
            <el-button type="primary" @click="goToDesigner()">新建报表</el-button>
            <el-button @click="exportReportsExcel">导出为Excel</el-button>
        </div>
        <!-- 报表列表 -->
        <el-table :data="filteredReports" border style="margin-top:14px">
            <el-table-column prop="name" label="报表名称" width="130" />
            <el-table-column prop="group" label="分组" width="100" />
            <el-table-column prop="desc" label="描述" width="280" />
            <el-table-column prop="chartType" label="类型" width="100">
                <template #default="scope">
                    <el-tag>{{ chartTypeMap[scope.row.chartType] }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="created" label="创建时间" width="110" />
            <el-table-column label="操作" width="380">
                <template #default="scope">
                    <el-button size="small" @click="goPreview(scope.row)">预览</el-button>

                    <el-button size="small" @click="goToDesigner(scope.row)">设计</el-button>
                    <el-button size="small" @click="shareReport(scope.row)">分享</el-button>
                    <el-button size="small" type="danger" @click="deleteReport(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 预览弹窗 -->
        <el-dialog v-model="previewDialogVisible" width="740px" :title="previewReportRow?.name || '报表预览'">
            <div style="margin-bottom:8px;">
                <el-radio-group v-model="previewChartType" size="small">
                    <el-radio-button label="table">表格</el-radio-button>
                    <el-radio-button label="bar">柱状图</el-radio-button>
                    <el-radio-button label="line">折线图</el-radio-button>
                    <el-radio-button label="pie">饼图</el-radio-button>
                    <el-radio-button label="funnel">漏斗图</el-radio-button>
                </el-radio-group>
                <el-button size="small" @click="exportPreviewExcel" style="margin-left:8px;">导出为Excel</el-button>
                <el-button size="small" @click="exportPreviewImg" style="margin-left:8px;">导出为图片</el-button>
            </div>
            <div v-if="previewChartType === 'table'">
                <el-table :data="previewReportRow?.data || []" border style="max-height:320px;">
                    <el-table-column v-for="f in previewReportRow?.fields || []" :key="f" :prop="f" :label="f" />
                </el-table>
            </div>
            <div v-else>
                <v-chart :option="getEchartsOption(previewReportRow, previewChartType)" autoresize
                    style="height:330px;" />
            </div>
        </el-dialog>

        <!-- 分享弹窗 -->
        <el-dialog v-model="shareDialogVisible" width="460px" title="报表分享">
            <div style="font-size:15px;word-break:break-all;">
                分享链接（仅本地有效）：<br />
                <span style="user-select:all;color:#1e80ff;">{{ shareLink }}</span>
            </div>
            <div style="margin-top:18px;">
                <el-button type="primary" size="small" @click="copyShareLink">复制链接</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref } from 'vue'
import * as XLSX from 'xlsx'
import VChart from 'vue-echarts'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

// 报表类型映射
const chartTypeMap = {
    table: '表格',
    bar: '柱状图',
    line: '折线图',
    pie: '饼图',
    funnel: '漏斗图'
}

// 分组选项
const groupOptions = ['销售', '生产', '市场', '人力', '财务']

// 模拟报表数据
function mockReports() {
    const data = []
    for (let i = 0; i < 12; i++) {
        const name = ['销售月报', '客户分布', '产能趋势', '市场分析', '员工结构', '财务汇总', '工单统计', '客户流失', '市场活动', '人员出勤', '费用分布', '预算分析'][i]
        const group = groupOptions[i % groupOptions.length]
        const fields = ['日期', '类别', '数值', '备注']
        // 模拟表格内容
        const reportData = Array.from({ length: 7 }, (_, idx) => ({
            日期: `2024-07-${String(idx + 1).padStart(2, '0')}`,
            类别: ['A', 'B', 'C', 'D'][i % 4],
            数值: Math.floor(Math.random() * 5000) + 500,
            备注: '-'
        }))
        data.push({
            id: Date.now() + i,
            name,
            group,
            desc: `这是${name}的多维统计分析报表。`,
            chartType: ['table', 'bar', 'line', 'pie', 'funnel'][i % 5],
            created: `2024-07-${String(10 + i).padStart(2, '0')}`,
            fields,
            data: reportData
        })
    }
    return data
}

function initReports() {
    const local = localStorage.getItem('reports')
    if (local) return JSON.parse(local)
    // 首次进入，自动写入mock数据
    const mock = mockReports()
    localStorage.setItem('reports', JSON.stringify(mock))
    return mock
}
const reports = ref(initReports())
const searchKeyword = ref('')
const selectedGroup = ref('')
const filteredReports = ref(reports.value)

// 页面每次进入都刷新（如用 keep-alive 建议 watch route）
onMounted(() => {
    reports.value = initReports()
    filterReports()
})

function filterReports() {
    let arr = reports.value
    if (searchKeyword.value) {
        arr = arr.filter(r => r.name.includes(searchKeyword.value) || r.desc.includes(searchKeyword.value))
    }
    if (selectedGroup.value) {
        arr = arr.filter(r => r.group === selectedGroup.value)
    }
    filteredReports.value = arr
}

// 新建/设计报表
function goToDesigner(row) {
    // 跳转到拖拽报表设计器，若 row 存在为编辑，否则为新建
    if (row) {
        router.push({ name: 'ReportDesigner', params: { id: row.id } })
    } else {
        router.push({ name: 'ReportDesigner' })
    }
}

// 预览相关
const previewDialogVisible = ref(false)
const previewReportRow = ref(null)
const previewChartType = ref('table')

function previewReport(row) {
    previewReportRow.value = row
    previewChartType.value = row.chartType || 'table'
    previewDialogVisible.value = true
}

// 动态生成 ECharts 配置
function getEchartsOption(row, type) {
    const data = row?.data || []
    if (!data.length) return {}
    // 以“日期”为X轴，“数值”为Y轴
    const xData = data.map(d => d.日期)
    const yData = data.map(d => d.数值)
    if (type === 'bar') {
        return {
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: xData },
            yAxis: { type: 'value' },
            series: [{ name: row.name, type: 'bar', data: yData, itemStyle: { borderRadius: 4 } }]
        }
    } else if (type === 'line') {
        return {
            tooltip: { trigger: 'axis' },
            xAxis: { type: 'category', data: xData },
            yAxis: { type: 'value' },
            series: [{ name: row.name, type: 'line', data: yData, smooth: true }]
        }
    } else if (type === 'pie') {
        return {
            tooltip: { trigger: 'item' },
            series: [
                {
                    name: row.name,
                    type: 'pie',
                    radius: ['38%', '75%'],
                    data: data.map(d => ({ value: d.数值, name: d.日期 }))
                }
            ]
        }
    } else if (type === 'funnel') {
        return {
            tooltip: { trigger: 'item' },
            series: [
                {
                    name: row.name,
                    type: 'funnel',
                    left: '10%',
                    width: '80%',
                    minSize: '40%',
                    label: { show: true, position: 'inside' },
                    data: data.map(d => ({ value: d.数值, name: d.日期 }))
                }
            ]
        }
    }
    return {}
}

// 删除报表
function deleteReport(row) {
    reports.value = reports.value.filter(r => r.id !== row.id)
    localStorage.setItem('reports', JSON.stringify(reports.value))
    filterReports()
    ElMessage.success('已删除')
}

// 导出全部报表为 Excel
function exportReportsExcel() {
    const excelData = reports.value.map(r => ({
        '报表名称': r.name,
        '分组': r.group,
        '描述': r.desc,
        '类型': chartTypeMap[r.chartType],
        '创建时间': r.created,
        '字段': r.fields.join(', ')
    }))
    const ws = XLSX.utils.json_to_sheet(excelData)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, '报表列表')
    XLSX.writeFile(wb, 'reports.xlsx')
}

// 预览导出 Excel
function exportPreviewExcel() {
    if (!previewReportRow.value) return
    const ws = XLSX.utils.json_to_sheet(previewReportRow.value.data)
    const wb = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(wb, ws, previewReportRow.value.name)
    XLSX.writeFile(wb, `${previewReportRow.value.name}.xlsx`)
}

// 预览导出图片
async function exportPreviewImg() {
    // 截取弹窗内容
    const dialogEl = document.querySelector('.el-dialog__body')
    if (!dialogEl) return
    const canvas = await html2canvas(dialogEl, { useCORS: true })
    const link = document.createElement('a')
    link.href = canvas.toDataURL('image/png')
    link.download = (previewReportRow.value?.name || '报表') + '.png'
    link.click()
}

// 分享功能
const shareDialogVisible = ref(false)
const shareLink = ref('')
function shareReport(row) {
    // 本地模拟，仅生成当前页面hash链接，实际可用配置json
    shareLink.value = `${window.location.origin}${window.location.pathname}#/report/report-preview/${row.id}`
    shareDialogVisible.value = true
}
function copyShareLink() {
    navigator.clipboard.writeText(shareLink.value)
    ElMessage.success('已复制')
}


function goPreview(row) {
    router.push({ name: 'ReportPreview', params: { id: row.id } })
}
</script>

<style scoped>
.multi-dim-report-page {
    padding: 24px;
}

.op-bar {
    margin-bottom: 12px;
    display: flex;
    gap: 12px;
    align-items: center;
}
</style>
